package cn.whb.hrm.service.impl;

import cn.whb.hrm.domain.VipUser;
import cn.whb.hrm.dto.SmsCodeDto;
import cn.whb.hrm.mapper.VipUserMapper;
import cn.whb.hrm.service.IVerifyService;
import cn.whb.hrm.util.AjaxResult;
import cn.whb.hrm.util.VerifyCodeUtils;
import cn.whb.hrm.util.encrypt.ValidUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import sun.misc.BASE64Encoder;

import javax.validation.Valid;
import javax.validation.constraints.NotBlank;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.concurrent.TimeUnit;

@Service
public class VerifyServiceImpl implements IVerifyService {

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private VipUserMapper vipUserMapper;

    @Override
    public AjaxResult imageCode(String key) {
        try {
            //非空校验
            ValidUtils.assertNotNull(key, "验证码请求错误");
            //生成验证码
            String code = VerifyCodeUtils.generateVerifyCode(4);
            //将验证码存在redis中
            redisTemplate.opsForValue().set(key, code, 5l, TimeUnit.MINUTES);
            //生成验证码图片
            BASE64Encoder encoder = new BASE64Encoder();
            ByteArrayOutputStream data = new ByteArrayOutputStream();
            VerifyCodeUtils.outputImage(100, 40, data, code);
            return AjaxResult.me().setResultObj(encoder.encode(data.toByteArray()));
        } catch (IOException e) {
            e.printStackTrace();
            return AjaxResult.me().setSuccess(false).setMessage("验证码获取错误");
        }
    }

    @Override
    public AjaxResult sendSmsCode(@Valid SmsCodeDto dto) {
        //非空验证用jsr303
        //查找手机号，校验手机号是否已注册
        VipUser vipUser = new VipUser();
        vipUser.setPhone(dto.getMobile());
        VipUser user = vipUserMapper.selectOne(vipUser);
        if (user!=null){
            throw new RuntimeException("该手机号已注册，请直接登录");
        }
        //校验图片验证码
        String code = dto.getImageCode();
        Object imgeCode = redisTemplate.opsForValue().get(dto.getImageCodeKey());
        if (imgeCode==null){
            throw new RuntimeException("验证码已过期，请重新获取");
        }
        if (!code.equalsIgnoreCase(imgeCode.toString())){
            throw new RuntimeException("验证码错误，请重新输入");
        }
        //获取手机验证码
        String phoneCode = VerifyCodeUtils.generateVerifyCode(6,"0123456789");
        //存入Redis中
        redisTemplate.opsForValue().set("REGIST::"+dto.getMobile(), phoneCode);
        System.out.println("您的验证码为："+phoneCode);
        return AjaxResult.me().setMessage("验证码已发送，请及时查收");
    }


}
